package com.example.interceptor;


import com.example.constant.Constants;
import com.example.model.UserInfo;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * Description:1、定义拦截器
 * User: 阿宾
 * Date: 2025-04-25
 * Time: 15:29
 */
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //true表示放行，false表示拦截
        log.info("LoginInterceptor preHandle");
        //获取session，并且判断session中存储的userinfo信息是否为空
        HttpSession session = request.getSession(true);
        UserInfo userInfo = (UserInfo)session.getAttribute(Constants.USER_SESSION_KEY);
        //因为拿到的session可能为空，所以需要判断
        if(userInfo == null || userInfo.getId() <= 0){
            //表示用户未登录
            response.setStatus(401);
            return false;
        }
        return true;
    }

/*    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
            throws Exception {
        log.info("LoginInterceptor postHandle");
        return;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        log.info("LoginInterceptor afterCompletion");
        return;
    }*/
}
